//
//  OAuthViewController.m
//  OC-微博
//
//  Created by Apple on 15/11/10.
//  Copyright © 2015年 Apple. All rights reserved.
//

#import "OAuthViewController.h"
@interface OAuthViewController () <UIWebViewDelegate>
@property (nonatomic, strong)UIWebView *webView;
@end

@implementation OAuthViewController
#pragma mark /*******************  视图生命周期  *******************/
- (void)loadView {
    self.view = self.webView;
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"登录新浪微博";
    //设置导航按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"自动填充" style:UIBarButtonItemStylePlain target:self action:@selector(autoFill)];
    self.webView.delegate = self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NetworkingTools shardTools].oauth]];
    
}
#pragma mark /*******************  懒加载  *******************/
//懒加载
-(UIWebView *)webView {
    
    if (_webView == nil) {
        _webView = [UIWebView new];
    }
    return _webView;
}

#pragma mark /*******************  关闭界面、自动填充 *******************/
- (void)close {
    //清除蒙板
    [SVProgressHUD dismiss];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)autoFill {
    NSString *js = @"document.getElementById('userId').value = '15712990611';"
    "document.getElementById('passwd').value = 'feiyang521yan';";
    // 让 webView 执行 js
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}
#pragma mark /*******************  WebView代理方法  *******************/
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    /// 将要加载请求的代理方法
    ///
    /// - parameter webView:        webView
    /// - parameter request:        将要加载的请求
    /// - parameter navigationType: navigationType，页面跳转的方式
    ///
    /// - returns: 返回 false 不加载，返回 true 继续加载
    /// 如果 iOS 的代理方法中有返回 bool，通常返回 true 很正常，返回 false 不能正常工作
    // 目标：如果是百度，就不加载
    // 1. 判断访问的主机是否是 www.baidu.com
    NSURL *url = request.URL;
    if (![url.host  isEqual: @"www.baidu.com"]){return YES;}
    // 2. 从百度地址的 url 中提取 `code=` 是否存在
    NSLog(@"%@",url.query);
    if (![url.query hasPrefix:@"code="]) {
        NSLog(@"取消授权");
        [self close];
        return NO;
    }
    // 3. 从 query 字符串中提取 `code=` 后面的授权码
    NSString *code = [url.query substringFromIndex:5];
    // 4. 加载 accessToken
    [[UserAccountViewModel shardViewModel]loadAccessTolen:code finished:^(BOOL isSuccessed) {
        // finished 的完整代码
        if (!isSuccessed) {
            [SVProgressHUD showInfoWithStatus:@"您的网络不给力"];
            NSLog(@"失败");
            //延迟操作
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self close];
            });
            return ;
        }
        NSLog(@"成功了");
        // dismissViewControllerAnimated 方法不会立即将控制器销毁
        [self dismissViewControllerAnimated:false completion:^{
            //停止蒙板
            [SVProgressHUD dismiss];
            [[NSNotificationCenter defaultCenter] postNotificationName:WBSwitchRootViewControllerNotification object:@"welcome"];
            
        }];
    }];
    return NO;
}
#pragma mark /*******************  蒙板  *******************/
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [SVProgressHUD show];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [SVProgressHUD dismiss];
}
@end
